package sg.techstudio.suntec.validator;

import java.util.Calendar;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.stereotype.Component;

import sg.techstudio.suntec.dao.EventContactDao;
import sg.techstudio.suntec.dao.RadiusDao;
import sg.techstudio.suntec.object.CPLoginObj;
import sg.techstudio.suntec.object.RestEventContactObj;
import sg.techstudio.suntec.object.WifiAccountObj;

@Component
public class CpValidator extends BaseValidator{
	private static final Log log = LogFactory.getLog(CpValidator.class);
	private static final String MAIN_ERROR_FIELD = "username";
	
	@Autowired
	private EventContactDao eDao;
	
	@Autowired
	private RadiusDao radiusDao;
	
	protected MessageContext getMessageContext(ValidationContext context) {
		return context.getMessageContext();
	}
	
	public void validateLoginForm(CPLoginObj cp, ValidationContext context) {
		log.debug("validateLoginForm() entry");
		MessageContext messages = getMessageContext(context);
		
		if(!validateEmptyString(cp.getUsername(), MAIN_ERROR_FIELD, messages) ||
				!validateEmptyString(cp.getPassword(), MAIN_ERROR_FIELD, messages))
			return;
		WifiAccountObj wifiAccountObj = eDao.getWifiAccountObj(cp.getUsername());
		if(wifiAccountObj==null || !StringUtils.equals(cp.getPassword(), wifiAccountObj.getWifiPassword())) {
			addMessage(MAIN_ERROR_FIELD, "cp.invalidcredential", messages);
			return;
		}
		if(radiusDao.countActiveSession(cp.getUsername(), cp.getMac()) >= wifiAccountObj.getMaxDevices()) {
			addMessage(MAIN_ERROR_FIELD, "cp.devicelimit", messages);
			return;
		}
		RestEventContactObj re = eDao.findEventByWifiAccount(wifiAccountObj);
		Calendar now = Calendar.getInstance();
		if(re==null || !re.isActive() || now.getTime().after(re.getActivateEndDate())
				|| now.getTime().before(re.getActivateStartDate())) {
			addMessage(MAIN_ERROR_FIELD, "cp.disabled", messages);
			return;
		}
	}
}
